---
import { isValidEmail, sendEmailVerificationLink } from "../../libs/email";

import { auth } from "../../libs/lucia";
import { SqliteError } from "better-sqlite3";
import { generateEmailVerificationToken } from "../../libs/token";
import Signup from '../../themes/default/signup.astro';

const { locale } = Astro.params;

let emailInput = "";
let errorMessage = "";

// check for form submissions
if (Astro.request.method === "POST") {
	const formData = await Astro.request.formData();
	const email = formData.get("email");
	const password = formData.get("password");
	if (typeof email === "string") {
		emailInput = email;
	}
	// basic check
	const validPassword =
		typeof password === "string" &&
		password.length >= 6 &&
		password.length <= 255;
	if (isValidEmail(email) && validPassword) {
		try {
			const user = await auth.createUser({
				key: {
					providerId: "email", // auth method
					providerUserId: email.toLowerCase(), // unique id when using "email" auth method
					password // hashed by Lucia
				},
				attributes: {
					username: email,
					email,
					email_verified: Number(false),
					nickname: email
				}
			});
			const session = await auth.createSession({
				userId: user.userId,
				attributes: {
					nickname: user.nickname
				}
			});
			Astro.locals.auth.setSession(session); // set session cookie
			const token = await generateEmailVerificationToken(user.userId);
			await sendEmailVerificationLink(token);
			return Astro.redirect("/email-verification", 302);
		} catch (e) {
			// this part depends on the database you're using
			// check for unique constraint error in user table
			if (e instanceof SqliteError && e.code === "SQLITE_CONSTRAINT_UNIQUE") {
				errorMessage = "Account already exists";
				Astro.response.status = 400;
			} else {
				console.log(e)
				errorMessage = "An unknown error occurred";
				Astro.response.status = 500;
			}
		}
	} else {
		errorMessage = "Invalid input";
		Astro.response.status = 400;
	}
}

const session = await Astro.locals.auth.validate();
if (session) {
	if (!session.user.emailVerified) {
		return Astro.redirect("/email-verification");
	}
	return Astro.redirect("/");
}
---
<div id="paypal-button-container-P-13W13561B8264054BMWB6KMY"></div>
<script src="https://www.paypal.com/sdk/js?client-id=AU2gR1TbNx8U-CNRJM6y-mi7YO61L3vVa65sQ262v-GiYcQsJasPHq4DExjPKAJef5oFNwlT_D6RvkY2&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script>
<script>
  paypal.Buttons({
      style: {
          shape: 'rect',
          color: 'gold',
          layout: 'vertical',
          label: 'subscribe'
      },
      createSubscription: function(data, actions) {
        return actions.subscription.create({
          /* Creates the subscription */
          plan_id: 'P-13W13561B8264054BMWB6KMY'
        });
      },
      onApprove: function(data, actions) {
        alert(data.subscriptionID); // You can add optional success message for the subscriber here
      }
  }).render('#paypal-button-container-P-13W13561B8264054BMWB6KMY'); // Renders the PayPal button
</script>
<Signup title="Sign up" emailInput={emailInput} errorMessage={errorMessage} />

